package com.example.uilearning;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AsyncTaskActivity extends Activity {
   private TextView textView;
   private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_async_task);
		textView=(TextView)findViewById(R.id.showPHP);
		button=(Button)findViewById(R.id.download);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DownTask downTask=new DownTask(AsyncTaskActivity.this);
				try {
					downTask.execute(new URL("http://www.crazyit.org/ethos.php"));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
		});
		
	}
	class DownTask extends AsyncTask<URL, Integer, String>{
        private int hasRead=0;
        private Context context;
        ProgressDialog progressDialog;
		public DownTask(Context context) {
			this.context=context;
		}
		@Override
		protected void onPreExecute() {
			progressDialog=new ProgressDialog(context);
			//设置对话框标题
			progressDialog.setTitle("任务正在执行中");
			//设置对话框显示内容
			progressDialog.setMessage("请等待......");
			progressDialog.setCancelable(false);
			//设置任务最大进度值
			progressDialog.setMax(202);
			//设置对话框进度风格
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			//设置对话框的进度条是否显示进度
			progressDialog.setIndeterminate(false);
			progressDialog.show();
			
		}

		@Override
		protected void onPostExecute(String result) {
			// 返回HTML页面内容
			textView.setText(result);
			progressDialog.dismiss();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			textView.setText("以读取"+values[0]+"行");
			progressDialog.setProgress(values[0]);
			
		}

		@Override
		protected String doInBackground(URL... params) {
			StringBuilder sb=new StringBuilder();
			BufferedReader br=null;
			URLConnection conn;
			try{
				conn=params[0].openConnection();
				br=new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				String line=null;
				while((line=br.readLine())!=null){
					sb.append(line+"\n");
					hasRead++;
					publishProgress(hasRead);
					Thread.sleep(200);
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}
		
	}
}
